package com.code.splider.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import com.code.splider.common.util.HttpClientUtils;
import com.code.splider.common.util.SXListUtils;
import com.code.splider.dao.EventDetailMapper;
import com.code.splider.dao.EventListMapper;
import com.code.splider.dao.EventMapper;
import com.code.splider.model.Event;
import com.code.splider.model.EventDetail;
import com.code.splider.model.EventList;
import com.code.splider.service.EventService;
import com.code.splider.service.ScorePanluService;

@Service()
public class EventServiceImpl implements EventService {

	// private static String url = "http://www.dszuqiu.com/data/all";
Logger log = Logger.getLogger(getClass());
	@Resource
	private EventMapper eventMapper;

	@Resource
	private EventListMapper eventListMapper;
	@Resource
	private EventDetailMapper eventDetailMapper;
	@Resource
	private ScorePanluService scorePanluService;

	@Override
	public void saveEvent(String url) {
//		Connection conn = Jsoup.connect(url).header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0");
		Elements el = null;
		try {
		 String html =	HttpClientUtils.getHttpClient(url);
		 Document doc = Jsoup.parse(html);
			delete();
			el = doc.getElementsByAttributeValue("class", "row");
			int i = 0;
			List<String> names = new ArrayList<>();
			for (Element element : el) {
				Element s = element.getElementsByAttributeValue("class", "small-1 columns text-right").first();
				Element divs = element.getElementsByAttributeValueEnding("class", "small-11 columns").first();
				if (s != null && divs != null) {
					Elements select = s.select("strong");
					Elements columns = divs.getElementsByAttributeValue("class", "small-11 columns");
					if (!select.isEmpty() && !columns.isEmpty()) {
						String name = select.html();
						if(!SXListUtils.isEmpty(names)&&names.contains(name)){
							continue;
						}
						names.add(name);
						i++;
						Event event = new Event();
						event.setName(name);
						event.setSort(i);
						event.setUpdateTime(new Date());
						this.eventMapper.insert(event);
						Elements a = columns.tagName("a").select("a[href]");
						List<EventList> list = new ArrayList<EventList>();
						int sort = 0;
						for (Element element2 : a) {
							sort++;
							EventList e = new EventList();
							e.setEventId(event.getId());
							e.setName(element2.html());
							e.setUrl(element2.attr("href"));
							e.setSort(sort);
							e.setUpdateTime(new Date());
							list.add(e);
						}
						this.eventListMapper.insertList(list);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void delete() {
		this.eventMapper.deleteAll();
		this.eventListMapper.deleteAll();
	}

	@Override
	public void saveEventDetail(String url) {
		List<String> zhibo = null;
		List<EventList> list = this.eventListMapper.selectAll();
		if (list != null) {
			zhibo = new ArrayList<>();
			List<EventDetail> zhiboListId = new ArrayList<>();
			this.deleteDetail();
			for (EventList event : list) {
				List<EventDetail> result =new ArrayList<EventDetail>();
				String league = event.getUrl();
				String temp =url+ league + "/p.";
				for (int i = 1; i < 50; i++) {
					String tempUrl = temp+i;
					List<EventDetail> details =	getdetail(tempUrl,event.getId());
					if(details==null||details.isEmpty()){
						break;
					}
					result.addAll(details);
					zhiboListId.addAll(details);
				}
				if(result!=null&&!result.isEmpty()){
					this.eventDetailMapper.insertList(result);
				}
			}
			if(zhiboListId!=null&&!zhiboListId.isEmpty()){
				for (EventDetail eventDetail : zhiboListId) {
					zhibo.add(eventDetail.getZhiboId());
				}
				scorePanluService.updateScorePanlu(zhibo);
			}
		}
	}

	private static List<EventDetail> getdetail(String url,Long id) {
//		Connection conn = Jsoup.connect(url).header("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
		Element el = null;
		List<EventDetail> list = new ArrayList<EventDetail>();
		try {
//			Document doc = conn.get();
			String html =	HttpClientUtils.getHttpClient(url);
			Document doc = Jsoup.parse(html);
			el = doc.getElementsByAttributeValue("class", "live-list-table").select("tbody").first();
			if(el!=null){
			Elements els = el.select("tr");
			for (Element element : els) {
				Elements tds = element.select("td");
				EventDetail det = new EventDetail();
				for (int i = 0; i < tds.size(); i++) {
					Element td = tds.get(i);
					switch (i) {
					case 0:
						det.setLeague(td.text());
						break;
					case 1:
						det.setCompetitionTime(td.text());
						break;
					case 2:
						try {
							Elements spans = td.select("span");
							if(spans!=null){
								for (int s=0; s<spans.size();s++) {
									if(s==0){
										String hrank= spans.get(0).text().replace("[", "").replace("]", "");
										det.setHomeRanking(hrank);
									}else if(s==1){
										String hrank= spans.get(1).text().replace("[", "").replace("]", "");
										det.setAwayRanking(hrank);	
									}
								}
							}
							Elements as = td.select("a");
							det.setHomeTeam(as.get(0).html());
							det.setAwayTeam(as.get(1).html());
							String[] strs = as.get(2).text().split("/");
							if(strs!=null){
								if(strs.length==0){
									det.setConcedePoints("-");
									det.setSizesBalls("-");
									det.setCorner("-");	
								}else if(strs.length==1){
									det.setConcedePoints(strs[0]);
									det.setSizesBalls("-");
									det.setCorner("-");		
								}else if(strs.length==2){
									det.setConcedePoints(strs[0]);
									det.setSizesBalls(strs[1]);
									det.setCorner("-");	
								}else{
									det.setConcedePoints(strs[0]);
									det.setSizesBalls(strs[1]);
									det.setCorner(strs[2]);		
								}
								Element link  = as.get(2);
								String str = link .attr("href");
								if(str!=null){
								 String[] hrefs  =	str.split("/");
								 det.setZhiboId(hrefs[hrefs.length-1]);
								}
							}
						} catch (Exception e) {
							System.out.println(td.select("a"));
							System.out.println("主客队 错误 url:  "+url);
						}

						break;
					case 5:
						try {
							String[] td3 = td.text().split(":");
							if(td3!=null){
								if(td3.length==0){
									det.setHomeCorner("-");
									det.setAwayCorner("-");	
								}else if(td3.length==1){
									det.setHomeCorner(td3[0]);
									det.setAwayCorner("-");	
								}else{
									det.setHomeCorner(td3[0]);
									det.setAwayCorner(td3[1]);	
								}
							}
						} catch (Exception e) {
							System.out.println("角球 错误 url:  "+url);
						}

						break;
					case 6:
						try {
							String[] td4 = td.text().split(":");
							if(td4!=null){
								if(td4.length==0){
									det.setHomeScore("-");
									det.setAwayScore("-");	
								}else if(td4.length==1){
									det.setHomeScore(td4[0]);
									det.setAwayScore("-");
								}else{
									det.setHomeScore(td4[0]);
									det.setAwayScore(td4[1]);	
								}
							}
						} catch (Exception e) {
							System.out.println("分数 错误  url:  "+url);
						}
						break;
					default:
						break;
					}
				}
				det.setEventListId(id);
				det.setUpdateTime(new Date());
				list.add(det);
			}
			}
		} catch (Exception ex) {
			System.out.println("异常   url:  "+url);
			ex.printStackTrace();
		}
		return list;
	}
	
	private void deleteDetail(){
		this.eventDetailMapper.deleteList();
	}
	
	public static void main(String[] args) {
		String url="http://www.dszuqiu.com/league/238/p.1";
		getdetail(url,21148L);
		
	}
}
